'use client';

import { useSocket } from '@/providers/socket-provider';
import {
  NEW_ORDER_EVENT,
  type NewOrderNotification,
} from '@/service/type/socket';
import dayjs from 'dayjs';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import QueryImage from '../common/query-image';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '../ui/dialog';

export default function NewOrderNotify({
  offlineNotify,
}: { offlineNotify: NewOrderNotification[] }) {
  const [open, setOpen] = useState(offlineNotify.length > 0);
  const socket = useSocket();
  const [orders, setOrders] = useState<NewOrderNotification[]>(offlineNotify);

  useEffect(() => {
    socket?.on(NEW_ORDER_EVENT, (args: NewOrderNotification) => {
      setOpen(true);
      setOrders((pre) => [...pre, args]);
    });
    return () => {
      socket?.off(NEW_ORDER_EVENT);
    };
  }, [socket]);

  return (
    <Dialog
      open={open}
      onOpenChange={(value) => {
        !value && setOrders([]);
        setOpen(value);
      }}
    >
      <DialogContent>
        <DialogHeader>
          <DialogTitle>您有新的订单</DialogTitle>
          <DialogDescription className="hidden" />
        </DialogHeader>
        <div className="space-y-5 max-h-[500px] scrollbar-none">
          {orders.map((order) => (
            <Link
              key={order.id}
              href={`/shop/order/${order.id}`}
              onClick={() => {
                setOpen(false);
                setOrders([]);
              }}
            >
              <div className="rounded-lg p-3 hover:bg-muted space-y-1">
                <div className="flex justify-between">
                  <div>订单ID：{order.id}</div>
                  <div className="text-xs">
                    {dayjs(order.createdAt).format('YYYY-MM-DD HH:mm:ss')}
                  </div>
                </div>
                <div className="text-xs text-muted-foreground">
                  {order.address}
                </div>
                <div className="flex gap-3">
                  {order.imageKeys.slice(0, 4).map((key: string) => (
                    <QueryImage
                      key={key}
                      imageKey={key}
                      wrapperClassName="w-20 h-12 rounded"
                      imgClassName="object-cover w-full h-full"
                    />
                  ))}
                </div>
              </div>
            </Link>
          ))}
        </div>
      </DialogContent>
    </Dialog>
  );
}
